<template>
  <div :class="{ expanded: expanded }" class="result-item">
    <div class="result-header" @click="toggleExpand">
      <div class="result-info">
        <el-checkbox
            :model-value="selected"
            :value="itemKey"
            @change="handleSelect"
            @click.stop
        />
        <div :class="['status-dot', validationResult.all_passed ? 'success' : 'error']"></div>
        <div class="result-details">
          <div class="document-number">{{ item.单据号 }}</div>
          <div class="document-time">{{ formatTime(item.推送时间) }}</div>
        </div>
      </div>

      <div class="result-summary">
        <div :class="['summary-badge', validationResult.all_passed ? 'success' : 'error']">
          <template v-if="validationResult.all_passed">
            <el-icon class="summary-icon" size="16">
              <Check/>
            </el-icon>
            <span>全部通过</span>
          </template>
          <template v-else>
            <el-icon class="summary-icon" size="16">
              <Close/>
            </el-icon>
            <span>{{ `${getFailedCount()} 失败` }}</span>
          </template>
        </div>
        <el-button
            class="delete-btn"
            type="text"
            @click.stop="handleDelete"
        >
          <el-icon size="16">
            <Delete/>
          </el-icon>
        </el-button>
        <div class="expand-icon">
          <el-icon size="16">
            <ArrowDown/>
          </el-icon>
        </div>
      </div>
    </div>

    <div v-if="expanded" class="result-details-panel">
      <!-- 概括结果 -->
      <div v-if="activeTab === 'summary'" class="summary-content">
        <h4>概括结果</h4>
        <div v-if="validationResult.item_names && validationResult.item_names.length > 0" class="validation-items">
          <div
              v-for="(name, index) in validationResult.item_names"
              :key="index"
              class="validation-item"
          >
            <span class="item-name">{{ name }}</span>
            <div class="item-status">
              <div
                  :class="['status-icon', validationResult.failed_items && validationResult.failed_items[index] ? 'failed' : 'success']">
                <el-icon size="14">
                  <Close v-if="validationResult.failed_items && validationResult.failed_items[index]"/>
                  <Check v-else/>
                </el-icon>
              </div>
              <span>{{
                  validationResult.failed_items && validationResult.failed_items[index] ? '未通过' : '通过'
                }}</span>
            </div>
          </div>
        </div>
        <div v-else-if="validationResult.results" class="validation-items">
          <div
              v-for="(result, name) in validationResult.results"
              :key="name"
              class="validation-item"
          >
            <span class="item-name">{{ name }}</span>
            <div class="item-status">
              <div
                  :class="['status-icon', Array.isArray(result) ? !result[0] : !result ? 'failed' : 'success']">
                <el-icon size="14">
                  <Close v-if="Array.isArray(result) ? !result[0] : !result"/>
                  <Check v-else/>
                </el-icon>
              </div>
              <span>{{
                  Array.isArray(result) ? !result[0] ? '未通过' : '通过' : !result ? '未通过' : '通过'
                }}</span>
            </div>
          </div>
        </div>
        <div v-else class="no-data">暂无概括信息</div>
      </div>

      <!-- 详细错误 -->
      <div v-if="activeTab === 'detailed'" class="detailed-content">
        <h4>详细错误信息</h4>
        <div v-if="item.详细错误信息 && item.详细错误信息.length > 0" class="error-items">
          <div
              v-for="(error, index) in item.详细错误信息"
              :key="index"
              class="error-item"
          >
            <div class="error-icon">
              <el-icon size="16">
                <WarningFilled/>
              </el-icon>
            </div>
            <div class="error-message">{{ error }}</div>
          </div>
        </div>
        <div v-else class="no-data">暂无详细错误信息</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {computed, ref} from 'vue'
import {ArrowDown, Check, Close, Delete, WarningFilled} from '@element-plus/icons-vue'

const props = defineProps({
  item: {
    type: Object,
    required: true
  },
  activeTab: {
    type: String,
    default: 'summary'
  },
  selected: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['select', 'delete'])

const expanded = ref(false)

    const itemKey = computed(() => `${props.item.单据号}_${props.item.推送时间}`)

    const validationResult = computed(() => {
      const result = props.item.校验结果

      // 处理复杂的字符串格式
      if (typeof result === 'string') {
        try {
          // 尝试解析JSON格式
          const parsed = JSON.parse(result)

          // 如果解析后是对象，直接返回
          if (typeof parsed === 'object' && parsed !== null) {
            return parsed
          }

          // 如果是简单的"校验通过"字符串
          if (result === '校验通过') {
            return {
              all_passed: true,
              failed_items: []
            }
          }
        } catch {
          // 如果JSON解析失败，检查是否是"校验通过"
          if (result === '校验通过') {
            return {
              all_passed: true,
              failed_items: []
            }
          }
        }
      }

      // 处理对象格式
      if (typeof result === 'object' && result !== null) {
        // 如果all_passed是字符串，需要特殊处理
        if (typeof result.all_passed === 'string') {
          try {
            // 尝试解析all_passed字符串中的JSON
            const allPassedParsed = JSON.parse(result.all_passed)

            // 如果解析成功，使用解析后的数据
            if (allPassedParsed && allPassedParsed.results) {
              const results = allPassedParsed.results
              const itemNames = Object.keys(results)
              const failedItems = itemNames.map(name => {
                const itemResult = results[name]
                // 检查是否是数组格式 [success, message]
                if (Array.isArray(itemResult)) {
                  return !itemResult[0] // 第一个元素是成功状态
                }
                return !itemResult // 直接是布尔值
              })

              return {
                all_passed: !failedItems.some(failed => failed),
                item_names: itemNames,
                failed_items: failedItems
              }
            }
          } catch {
            // 如果解析失败，回退到简单处理
            return {
              all_passed: result.all_passed === '校验通过' || result.all_passed === 'true',
              failed_items: result.failed_items || []
            }
          }
        }
        
        return result
      }

      // 默认返回
      return {
        all_passed: false,
        failed_items: [{name: '未知错误'}]
      }
    })

    const formatTime = (timeStr) => {
      if (!timeStr) return '-'
      try {
        const date = new Date(timeStr)
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        })
      } catch {
        return timeStr
      }
    }

    const toggleExpand = () => {
      expanded.value = !expanded.value
    }

    const handleSelect = (checked) => {
      emit('select', itemKey.value, checked)
    }

    const handleDelete = () => {
      emit('delete', props.item)
    }

    const getFailedCount = () => {
      if (validationResult.value.failed_items) {
        if (Array.isArray(validationResult.value.failed_items)) {
          return validationResult.value.failed_items.filter(item => item).length
        }
        return validationResult.value.failed_items.length || 0
      }
      return 0
    }


</script>

<style scoped>
/* 结果列表 */
.result-item {
  border-bottom: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

.result-item:hover {
  background: #f8f9fa;
}

.result-item:last-child {
  border-bottom: none;
}

.result-header {
  padding: 20px 30px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #333; /* 确保文字颜色不受父级影响 */
}

.result-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.status-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.status-dot.success {
  background: #28a745;
}

.status-dot.error {
  background: #dc3545;
}

.result-details {
  flex: 1;
}

.document-number {
  font-weight: 600;
  color: #333;
  font-size: 1.1rem;
  margin-bottom: 4px;
}

.document-time {
  color: #666;
  font-size: 0.9rem;
}

.result-summary {
  display: flex;
  align-items: center;
  gap: 15px;
}

.summary-badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 500;
  min-width: 80px;
  text-align: center;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.summary-badge.success {
  background: #d4edda;
  color: #155724;
}

.summary-badge.error {
  background: #f8d7da;
  color: #721c24;
}

.delete-btn {
  color: #ff4d4f;
}

.delete-btn:hover {
  background: #fff2f0;
}

.expand-icon {
  transition: transform 0.3s ease;
  color: #666;
  font-size: 0.8rem;
}

.result-item.expanded .expand-icon {
  transform: rotate(180deg);
}

/* 详情面板 */
.result-details-panel {
  background: #f8f9fa;
  padding: 20px 30px;
  border-top: 1px solid #e9ecef;
}

.summary-content h4,
.detailed-content h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 1rem;
  font-weight: 600;
}

.validation-items,
.error-items {
  space-y: 10px;
}

.validation-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #e9ecef;
}

.validation-item:last-child {
  border-bottom: none;
}

.item-name {
  color: #333;
  font-weight: 500;
}

.item-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-icon {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: white;
  font-weight: bold;
}

.status-icon.success {
  background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
  box-shadow: 0 2px 8px rgba(40, 167, 69, 0.3);
}

.status-icon.failed {
  background: linear-gradient(135deg, #dc3545 0%, #e74c3c 100%);
  box-shadow: 0 2px 8px rgba(220, 53, 69, 0.3);
}

.error-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  padding: 12px 0;
  border-bottom: 1px solid #e9ecef;
}

.error-item:last-child {
  border-bottom: none;
}

.error-icon {
  width: 20px;
  height: 20px;
  background: linear-gradient(135deg, #ffc107 0%, #ffca2c 100%);
  color: #856404;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  flex-shrink: 0;
  font-size: 12px;
  box-shadow: 0 2px 8px rgba(255, 193, 7, 0.3);
}

.error-message {
  color: #333;
  line-height: 1.5;
  flex: 1;
}

.no-data {
  color: #666;
  font-style: italic;
  text-align: center;
  padding: 20px;
}

@media (max-width: 768px) {
  .result-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .result-details-panel {
    padding: 15px 20px;
  }
}
</style>